/**
 * User Store
 */

import expired from '@/config/expired'
import * as cache from '@/util/cache'
import md5 from 'js-md5'
const tokeKey = 'spsp' + md5('token')
const infoKey = 'sfsf' + md5('info')
const referrerKey = 'srsr' + md5('referrer')
const subscribeKey = 'sub' + md5('subscribe')

export default {
  namespaced: true,
  state: {
    token: null,
    info: null,
    /**
     * register referrer id
     */
    referrer: null,
    subscribe: null,
  },
  getters: {
    token: state => {
      if (state.token === null) {
        state.token = cache.get(tokeKey)
      }
      return state.token
    },
    info: state => {
      if (state.info === null) {
        state.info = cache.get(infoKey)
      }
      return state.info
    },
    referrer: state => {
      if (state.referrer === null) {
        state.referrer = cache.get(referrerKey)
      }
      return state.referrer
    },
    subscribe: state => {
      if (state.subscribe === null) {
        state.subscribe = cache.get(subscribeKey)
      }
      return state.subscribe
    }
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      cache.save(tokeKey, token, expired.userToken)
    },
    SET_INFO: (state, info) => {
      state.info = info
      cache.save(infoKey, info, expired.referrer)
    },
    SET_LOGOUT: (state) => {
      state.token = null
      state.info = null
      cache.remove(tokeKey)
      cache.remove(infoKey)
    },
    SET_REFERRER: (state, referrer) => {
      state.referrer = referrer
      cache.save(referrerKey, referrer)
    },
    SET_SUBSCRIBE: (state, data) => {
      state.subscribe = data
      cache.save(subscribeKey, data)
    }
  },
  actions: {
    login: ({ commit }, token) => {
      commit('SET_TOKEN', token)
    },
    set_info: ({ commit }, info) => {
      commit('SET_INFO', info)
    },
    logout: ({ commit }) => {
      commit('SET_LOGOUT')
    },
    set_referrer: ({ commit }, referrer) => {
      commit('SET_REFERRER', referrer)
    },
    set_subscribe: ({ commit }, data) => {
      commit('SET_SUBSCRIBE', data)
    }
  }
}
